package com.cyq.dascma.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cyq.dascma.constant.ValidaEnum;
import com.cyq.dascma.dto.CourseDto;
import com.cyq.dascma.entity.Course;
    import com.cyq.dascma.exception.ServiceException;
import com.cyq.dascma.handler.valida.impl.CourseValidaImpl;
import com.cyq.dascma.result.Result;
import com.cyq.dascma.result.ResultGenerator;
import com.cyq.dascma.service.CourseService;
import com.cyq.dascma.service.TeacherService;
import com.cyq.dascma.util.RequestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.swing.text.html.Option;
import java.util.*;
import java.util.stream.Collectors;

/**
 * dingwen
 * 2021/4/4 17:14
 **/
@Api(tags = "课程管理")
@RestController
@RequestMapping("/course")
public class CourseController {
    private final CourseService courseService;
    private final TeacherService teacherService;

    @Autowired
    CourseController(CourseService courseService, TeacherService teacherService) {
        this.courseService = courseService;
        this.teacherService = teacherService;
    }

    /*
     *分页查询所有课程信息列表  info
     * @param []
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation(value = "分页查询所有课程信息列表  info")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "teacherName", value = "授课教师姓名", required = false),
            @ApiImplicitParam(name = "courseId", value = "课程编号", required = false),
            @ApiImplicitParam(name = "courseName", value = "课程名称", required = false),
            @ApiImplicitParam(name = "courseType", value = "课程类型【0：专业必修 1:专业选修】", required = false),
            @ApiImplicitParam(name = "teacherId", value = "授课教师教工号", required = false),
            @ApiImplicitParam(name = "pageSize", value = "每页多少条", required = true),
            @ApiImplicitParam(name = "pageNum", value = "第几页", required = true),
    })

    @GetMapping("info/page")
    public Result get(@RequestParam(value = "teacherName", required = false) String teacherName,
                      @RequestParam(value = "courseId", required = false) String courseId,
                      @RequestParam(value = "courseType", required = false) String courseType,
                      @RequestParam(value = "courseName", required = false) String courseName,
                      @RequestParam(value = "teacherId", required = false) String teacherId,
                      @RequestParam(value = "pageSize") Integer pageSize,
                      @RequestParam("pageNum") Integer pageNum, HttpServletRequest request) {
        Map<String, Object> params = RequestUtil.getParameterMap(request);
        params.put("offset", ((pageNum - 1) * pageSize));
        params.put("limit", (pageSize));
        List<CourseDto> courseInfoList = courseService.findCourseInfoList(params);
        return ResultGenerator.genOkResult(courseInfoList);
    }

    /*
     *新增课程信息
     * @param [course]
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("新增课程信息")
    @ApiImplicitParam(value = "课程信息实体", name = "course", required = true, dataType = "course", paramType = "body")
    @PostMapping("/add")
    public Result add(@RequestBody Course course) {
        try {
            new CourseValidaImpl().valida(ValidaEnum.ADD, course);
        } catch (ServiceException serviceException) {
            return serviceException.result();
        }

        boolean flag = courseService.save(course);

        return flag ? ResultGenerator.genOkResult(course).setMessage("成功新增课程信息") : ResultGenerator.genFailureResult("新增课程信息失败");
    }

    /*
     *更新课程信息
     * @param [course]
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("更新课程信息")
    @ApiImplicitParam(value = "课程信息实体", name = "course", required = true, dataType = "course", paramType = "body")
    @PutMapping("/modify")
    public Result modify(@RequestBody Course course) {
        try {
            new CourseValidaImpl().valida(ValidaEnum.MODIFY, course);
        } catch (ServiceException serviceException) {
            return serviceException.result();
        }

        boolean flag = courseService.update(course, new UpdateWrapper<Course>()
                .and(wrapperCourseId -> wrapperCourseId.eq("course_id", course.getCourseId()))
                .and(wrapperTeacherId -> wrapperTeacherId.eq("teacher_id", course.getTeacherId())));

        return flag ? ResultGenerator.genOkResult(course).setMessage("更新课程信息成功") : ResultGenerator.genFailureResult("更新课程信息失败");
    }

    /*
     *删除课程信息
     * @param [courseId,teacherId]
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("删除课程信息")
    @ApiImplicitParam(value = "课程ID", name = "courseId")
    @DeleteMapping("/remove/{courseId}/{teacherId}")
    public Result remove(@PathVariable String courseId,@PathVariable String teacherId) {
        boolean flag = courseService.remove(new QueryWrapper<Course>()
                .and(wrapperCourseId -> wrapperCourseId.eq("course_id", courseId))
                .and(wrapperTeacherId -> wrapperTeacherId.eq("teacher_id", teacherId)));
        return flag ? ResultGenerator.genOkResult(courseId).setMessage("删除课程信息成功") : ResultGenerator.genFailureResult("删除课程信息失败");
    }


    /*
     *查询课程总记录条数
     * @param []
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("查询课程总记录条数")
    @GetMapping("/total")
    public Result getTotal() {
        return ResultGenerator.genOkResult(courseService.count());
    }


    /*
     *查询所有课程的的ID & name & year 信息
     * @param []
     * @return com.cyq.dascma.result.Result
     */
    @ApiOperation("查询所有课程的的ID & name & year 信息")
    @ApiImplicitParam(value = "根据课程编号查询教授这门课程的老师")
    @GetMapping("/ins")
    public Result get(@RequestParam(required = false) String courseId){
        List<Course> courseList = courseService.list(new QueryWrapper<Course>().select("course_id","teacher_id","course_name")
                                                .eq(StringUtils.hasText(courseId),"course_id",courseId));

        if (!StringUtils.hasText(courseId)){
            courseList = courseList.stream().collect(Collectors
                    .collectingAndThen(Collectors
                            .toCollection(() -> new TreeSet<>(Comparator
                                    .comparing(Course::getCourseId))), ArrayList::new));
        }
        List<CourseDto> courseDtoList = new ArrayList<>();
        courseList.stream().sequential().forEach( course -> {
            CourseDto courseDto = new CourseDto();
            courseDto.setTeacherName(teacherService.getById(course.getTeacherId()).getTeacherName());
            courseDto.setTeacherId(course.getTeacherId());
            courseDto.setCourseId(course.getCourseId());
            courseDto.setCourseName(course.getCourseName());
            courseDtoList.add(courseDto);
        });
        return  ResultGenerator.genOkResult(courseDtoList);
    }
}
